import { useState } from 'react';

function useLocalStorage(key, initialValue) {
  // 从 localStorage 获取数据，若没有则使用 initialValue
  const storedValue = localStorage.getItem(key);
  const [value, setValue] = useState(() => {
    return storedValue ? JSON.parse(storedValue) : initialValue;
  });

  // 在 value 改变时同步到 localStorage
  const setStoredValue = (newValue) => {
    setValue(newValue);
    localStorage.setItem(key, JSON.stringify(newValue)); // 保存为字符串
  };

  return [value, setStoredValue];
}

export default useLocalStorage;
